'use client';
import { useState, useRef, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import './ChatPage.css';

// 1. 匹配后端完整数据结构的接口定义
interface ContextItem {
  id: string;
  role: 'system' | 'user' | 'agent';
  content: string;
  date: string;
}

interface Mask {
  id: number; // 后端maskId为数字类型（如1、3）
  name: string;
  avatar: string;
  context: ContextItem[];
}

interface ChatMessage {
  id?: string;
  role: 'user' | 'agent';
  content: string;
  date: string;
  maskId?: string; // 前端传递时转为字符串（与URL参数一致）
  sessionId: string;
}

interface Session {
  id: string;
  creatTime: string;
  lastUpdate: string;
  topic: string;
  messages: ChatMessage[];
  mask: Mask;
}

interface Message extends ChatMessage {
  timestamp: Date;
}

// 2. 角色转换：适配DeepSeek API（agent→assistant）
const convertToApiRole = (role: 'user' | 'agent'): 'user' | 'assistant' => {
  return role === 'agent' ? 'assistant' : 'user';
};

export default function ChatPage() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [systemPrompt, setSystemPrompt] = useState<string>('You are a helpful assistant.'); // 默认为通用提示
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [searchParams] = useSearchParams();

  // 从URL获取参数（maskId为字符串，需与后端数字ID匹配）
  const sessionId = searchParams.get('sessionId');
  const maskId = searchParams.get('maskId'); // 如"1"（对应后端mask.id=1）
  const maskName = searchParams.get('maskName');

  // 3. 核心逻辑：根据maskId从后端数据中提取system提示
  useEffect(() => {
    if (!maskId || !sessionId) return;

    // 调用后端/session/all接口，获取包含mask的会话数据
    const fetchSystemPromptByMaskId = async () => {
      try {
        const response = await fetch('http://localhost:8080/session/all');
        if (!response.ok) throw new Error(`获取会话数据失败: ${response.status}`);
        
        const allSessions: Session[] = await response.json();
        // 步骤1：找到包含目标maskId的会话（任意一个关联该mask的会话即可）
        const targetSession = allSessions.find(
          session => session.mask.id.toString() === maskId // 数字mask.id转为字符串匹配URL参数
        );

        if (!targetSession) {
          console.warn(`未找到maskId=${maskId}对应的会话，使用默认system提示`);
          return;
        }

        // 步骤2：提取该mask的system角色提示（取第一个system类型的context）
        const systemContext = targetSession.mask.context.find(
          ctx => ctx.role === 'system'
        );

        if (systemContext) {
          setSystemPrompt(systemContext.content); // 更新为面具专属提示
          console.log(`已加载mask专属system提示: ${systemContext.content}`);
        } else {
          console.warn(`maskId=${maskId}未配置system提示，使用默认提示`);
        }

      } catch (error) {
        console.error('提取system提示失败:', error);
      }
    };

    fetchSystemPromptByMaskId();
  }, [maskId, sessionId]);

  // 4. 自动滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // 5. 保存消息到后端
  const saveMessageToBackend = async (message: ChatMessage) => {
    try {
      const response = await fetch(`http://localhost:8080/session/message/add?sessionId=${message.sessionId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(message)
      });

      if (!response.ok) throw new Error(`保存消息失败: ${response.status}`);
      const result = await response.text();
      console.log('消息保存结果:', result);
      return result;
    } catch (error) {
      console.error('保存消息到后端时出错:', error);
      throw error;
    }
  };

  // 6. 发送消息到AI（包含mask专属system提示）
  const sendMessage = async () => {
    if (!input.trim() || isLoading || !sessionId) return;

    // 步骤1：创建用户消息
    const now = new Date();
    const userMessage: Message = {
      role: 'user',
      content: input.trim(),
      timestamp: now,
      date: now.toISOString(),
      sessionId: sessionId,
      maskId: maskId || undefined
    };
    
    // 步骤2：更新UI显示用户消息
    setMessages(prev => [...prev, userMessage]);
    setInput('');
    setIsLoading(true);

    try {
      // 步骤3：保存用户消息到后端
      await saveMessageToBackend(userMessage);

      // 步骤4：构建AI请求参数（核心：携带mask专属system提示）
      const apiMessages = [
        // 第一句话：使用mask的system提示（而非默认提示）
        { role: 'system' as const, content: systemPrompt },
        // 历史消息：转换角色（agent→assistant）
        ...messages.map(msg => ({
          role: convertToApiRole(msg.role),
          content: msg.content
        })),
        // 当前用户消息
        { role: 'user' as const, content: input.trim() }
      ];

      // 步骤5：调用DeepSeek API
      const response = await fetch('https://api.deepseek.com/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer sk-d230429752104f10b2ab1b8c24b6f813`
        },
        body: JSON.stringify({
          model: 'deepseek-chat',
          messages: apiMessages, // 包含mask专属system提示
          stream: false,
          temperature: 0.7, // API必需参数
          max_tokens: 2048 // 限制响应长度
        })
      });

      if (!response.ok) {
        const errorDetails = await response.text().catch(() => '无详细错误信息');
        throw new Error(`API请求失败: ${response.status} - ${errorDetails}`);
      }

      // 步骤6：处理AI回复
      const data = await response.json();
      const aiContent = data.choices[0].message.content;
      const assistantNow = new Date();
      const assistantMessage: Message = {
        role: 'agent',
        content: aiContent,
        timestamp: assistantNow,
        date: assistantNow.toISOString(),
        sessionId: sessionId,
        maskId: maskId || undefined
      };

      // 步骤7：更新UI并保存AI回复
      setMessages(prev => [...prev, assistantMessage]);
      await saveMessageToBackend(assistantMessage);

    } catch (error) {
      // 错误处理：显示具体错误信息
      const errorMsg = error instanceof Error ? error.message : '未知错误';
      console.error('发送消息时出错:', errorMsg);
      const errorNow = new Date();
      const errorMessage: Message = {
        role: 'agent',
        content: `抱歉，获取回复失败：${errorMsg}`,
        timestamp: errorNow,
        date: errorNow.toISOString(),
        sessionId: sessionId,
        maskId: maskId || undefined
      };
      setMessages(prev => [...prev, errorMessage]);
      try {
        await saveMessageToBackend(errorMessage);
      } catch (err) {
        console.error('保存错误消息失败:', err);
      }
    } finally {
      setIsLoading(false);
    }
  };

  // 7. 回车发送（Shift+Enter换行）
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  return (
    <div className="deepseek-chat-container">
      <div className="chat-header">
        <div className="chat-logo"><span>{maskName || '未知面具'}</span></div>
        {!sessionId && (
          <div className="session-warning">警告：未找到会话ID，消息可能无法保存</div>
        )}
      </div>
      
      <div className="chat-messages">
        {messages.length === 0 && (
          <div className="empty-messages">
            <p>开始与{maskName || 'AI'}对话吧～</p>
            {systemPrompt && systemPrompt !== 'You are a helpful assistant.' && (
              <p className="system-prompt-hint">（AI将遵循提示：{systemPrompt}）</p>
            )}
          </div>
        )}
        
        {messages.map((msg, index) => (
          <div 
            key={index + msg.timestamp.getTime()} // 避免索引重复导致的渲染问题
            className={`message ${msg.role === 'user' ? 'user-message' : 'assistant-message'}`}
          >
            <div className="message-sender">
              {msg.role === 'user' ? '你' : maskName || 'DeepSeek'}
            </div>
            <div className="message-content">{msg.content}</div>
            <div className="message-time">
              {msg.timestamp.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
              })}
            </div>
          </div>
        ))}
        
        {isLoading && (
          <div className="message assistant-message loading">
            <div className="message-sender">{maskName || 'DeepSeek'}</div>
            <div className="message-content">
              <div className="typing-indicator">
                <span>.</span>
                <span>.</span>
                <span>.</span>
              </div>
            </div>
          </div>
        )}
        
        <div ref={messagesEndRef} />
      </div>
      
      <div className="chat-input-area">
        <textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyPress={handleKeyPress}
          placeholder="输入消息..."
          className="message-input"
          disabled={isLoading || !sessionId}
        />
        <button 
          onClick={sendMessage} 
          className="send-button"
          disabled={!input.trim() || isLoading || !sessionId}
        >
          发送
        </button>
      </div>
    </div>
  );
}